// pages/detail-search/index.js
import {
    getSearchHost,
    getSearchSuggest,
    getSearchResult
} from "../../service/api_search"
import debounce from "../../utils/debounce"
import stringToNodes from '../../utils/string2nodes'

//搜索进行防抖处理
const debounceGetSearchSuggest = debounce(getSearchSuggest, 300)
Page({

    /**
     * 页面的初始数据
     */
    data: {
        hotKeywords: [],
        searchValue: "",
        suggestSongs: [],
        suggestSongsNodes: [],
        resultSongs: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //获取页面数据
        this.getPageData()
    },
    getPageData: function () {
        getSearchHost().then(res => {
            this.setData({
                hotKeywords: res.result.hots
            })
        })
    },
    /**
     * 搜索框绑定事件
     */
    handleSearchChange: function (event) {
        //输入值
        const searchValue = event.detail
        this.setData({
            searchValue: searchValue
        })
        //判断关键字为空字符的处理逻辑
        if (!searchValue.length) {
            this.setData({
                suggestSongs: [],
                resultSongs: []
            })
            debounceGetSearchSuggest.cancel()
            return
        }
        //获取联想结果
        debounceGetSearchSuggest(searchValue).then(res => {
            // 1.获取建议的关键字歌曲
            const suggestSongs = res.result.allMatch
            this.setData({
                suggestSongs
            })
            // 2.转成nodes节点
            if (!suggestSongs) {
                return
            }
            const suggestKeywords = suggestSongs.map(item => item.keyword)
            const suggestSongsNodes = []
            for (const keyword of suggestKeywords) {
                const nodes = stringToNodes(keyword, searchValue)
                suggestSongsNodes.push(nodes)
            }
            this.setData({
                suggestSongsNodes
            })
        })
    },
    /**
     * 搜索
     */
    handleSearchAction: function () {
        // 保存一下searchValue

        const searchValue = this.data.searchValue
        getSearchResult(searchValue).then(res => {
            this.setData({
                resultSongs: res.result.songs
            })
        })
    },
    /**
     * 联想结果回车
     * @param {*} event 
     */
    handleKeywordItemClick: function (event) {
        // 1.获取点击的关键字
        const keyword = event.currentTarget.dataset.keyword

        // 2.将关键设置到searchValue中
        this.setData({
            searchValue: keyword
        })

        // 3.发送网络请求
        this.handleSearchAction()
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
})